import React, { Component } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import CommentSocialBar from 'component/SocialBars/CommentSocialBar';
import SmallProfileBar from 'component/ProfileBars/SmallProfileBar';
import Text from 'component/Text';

const Root = styled.div``;

const Container = styled.div`
  margin-top: 8px;
`;

class CommentItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      injected: [false, false],
      display: [false, false]
    };
    this.inject = this.inject.bind(this);
    this.suck = this.suck.bind(this);
  }

  inject(index) {
    const { injected } = this.state;
    if (injected[index]) {
      return;
    }
    injected[index] = true;
    this.setState({ injected });
  }

  show(index = 1) {
    const { display } = this.state;
    if (display[index]) {
      return;
    }
    display[index] = true;
    this.setState({ display });
  }

  hide(index = 1) {
    const { display } = this.state;
    if (!display[index]) {
      return;
    }
    display[index] = false;
    this.setState({ display });
  }

  toggle(index = 1) {
    const { display } = this.state;
    if (display[index]) {
      this.hide(index);
    } else {
      this.show(index);
    }
  }

  suck(index) {
    const { injected } = this.state;
    injected[index] = false;
    this.setState({ injected });
  }

  render() {
    const { data, injectComponent } = this.props;
    const [injectComponent0, injectComponent1] = injectComponent;
    const { injected, display } = this.state;

    return (
      <Root>
        <SmallProfileBar data={data.profile} />
        <Container>
          <Text>{data.content}</Text>
        </Container>
        <CommentSocialBar
          id={data.id}
          data={data.social}
          onClickReply={() => {
            this.inject(0);
            if (data.social.repliesCounts) {
              this.inject(1);
              this.show(1);
            }
          }}
          onWatchReplies={() => {
            if (data.social.repliesCounts) {
              this.inject(1);
              this.toggle(1);
            }
          }}
        />
        {injected[0] &&
          injectComponent0({
            onBlur: () => this.suck(0)
          })}
        {injected[1] &&
          injectComponent1({
            style: {
              display: display[1] ? 'block' : 'none'
            }
          })}
      </Root>
    );
  }
}

CommentItem.propTypes = {
  data: PropTypes.shape({
    profile: PropTypes.object.isRequired,
    content: PropTypes.string.isRequired,
    social: PropTypes.shape({
      repliesCounts: PropTypes.number.isRequired
    }).isRequired
  }).isRequired,
  injectComponent: PropTypes.arrayOf(PropTypes.func).isRequired
};

export default CommentItem;
